<template>
  <view>
    <nav-bar :page-title="lang.page_name"/>
    <view style="overflow:hidden;margin:0 30rpx 0 30rpx; " :class="locale">
      <view class="upload-box">

        <!-- 照片选自框大 box-->
        <view class="flex-column gap-30">
          <view class="column-center gap-20">
            <view class="upload-card-box">
              <!-- 驾驶证正面-->
              <view v-if="driveFront === ''" hover-class="hover" @click="showUploadImage(0)">
                <view class="column-center icon-card-box">
                  <view class="flex-column icon-card">
                    <u-icon size="44px" color="#1073FF" name="camera"/>
                  </view>
                </view>
                <image class="uploaded-image" src="/static/print_id/drive_front.jpg"/>
              </view>

              <template v-else>
                <view class="column-center gap-20" @click="closeDrive(0)">
                  <view class="close-icon-box">
                    <u-icon size="26px" color="#0009" name="close-circle-fill"/>
                  </view>
                </view>
                <view @click="onEditImage(0)">
                  <image class="uploaded-image" :src="driveFront"/>
                </view>
              </template>
            </view>
            <view class="text-32">{{ lang.drive_front }}</view>
          </view>


          <!-- 驾驶证后面-->
          <view class="column-center gap-20">
            <view class="upload-card-box">
              <!-- 上传照片前-->
              <view v-if="driveAfter === ''" @click="showUploadImage(1)" hover-class="hover">
                <view class="column-center icon-card-box">
                  <view class="flex-column icon-card">
                    <u-icon size="44px" color="#1073FF" name="camera"/>
                  </view>
                </view>
                <image class="uploaded-image" src="/static/print_id/drive_after.jpg"/>
              </view>

              <!-- 上传照片后-->
              <template v-else>
                <view class="close-icon-box" @click="closeDrive(1)">
                  <u-icon size="26px" color="#0009" name="close-circle-fill"/>
                </view>
                <view @click="onEditImage(1)">
                  <image class="uploaded-image" :src="driveAfter"/>
                </view>
              </template>
            </view>
            <view class="text-32">{{ lang.drive_after }}</view>
          </view>
        </view>
      </view>

      <view style="margin-top: 30rpx;">
        <u-button
            :disabled="!driveFront && !driveAfter" shape="circle" @click="drawAndShareImage" size="large"
            color="#1073FF" :customStyle="{fontSize: '32rpx' }">
          {{ otherLang.print }}
        </u-button>
      </view>

      <!-- 给服务器发送的和打印出的-->
      <view class="canvas">
        <canvas style="width: 1588px; height: 2246px; " canvas-id="driveCanvas" id="driveCanvas"/>
      </view>


      <!-- 选择弹窗-->
      <upload-select-popup
          :show-popup="showUploadPopup" @choose-message="chooseMessage" @choose-image="chooseImage"
          @close-popup="showUploadPopup = false"/>
    </view>
  </view>
</template>

<script>
import navBar from "@/components/nav-bar/nav-bar.vue";
import my_upload_card from "@/components/my_upload_card/index.vue";
import uploadSelectPopup from "@/components/upload-select-popup/upload-select-popup.vue";
import tips from "@/utils/tips";
import {uploadImageServer} from "@/services/office";

export default {
  components: {navBar, uploadSelectPopup, my_upload_card},
  computed: {
    lang() {
      return this.$t('print_drive')
    }
  },
  data() {
    return {
      showUploadPopup: false,
      clickType: 0, // 上传的类型，0为正面，1为背面
      driveFront: "", // 驾驶证前面
      driveAfter: "", // 驾驶证后面
      uploadProgress: 0,
    }
  },
  methods: {
    // 选自 正面上传还是背面上传
    showUploadImage(type) {
      this.clickType = type;
      this.showUploadPopup = true;
    },

    // 微信里上传
    chooseMessage() {
      const that = this;
      uni.chooseMessageFile({
        count: 1,
        type: 'image',
        success(res) {
          console.log('上传照片-------------------', res)
          that.editImageChange(res.tempFiles[0].path)
        }
      })
    },

    // 本地图片上传或拍照
    chooseImage(index) {
      const that = this;
      const sourceTypes = ['camera', 'album'];
      uni.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: [sourceTypes[index]],
        sizeType: ['original', 'compressed'],
        success: function (res) {
          that.editImageChange(res.tempFiles[0].tempFilePath)
        }
      })
    },

    // 照片编译
    editImageChange(src) {
      uni.editImage({
        src,
        success: ({tempFilePath}) => {
          // 根据 clickType 更新 driveFront 或 driveAfter
          if (this.clickType === 0) {
            this.driveFront = tempFilePath;
          } else {
            this.driveAfter = tempFilePath;
          }
        },
      })
    },

    // 删除照片
    closeDrive(e) {
      const drives = [this.driveFront, this.driveAfter]; // 将照片存储在数组中
      drives[e] = ''; // 根据索引删除对应照片
      [this.driveFront, this.driveAfter] = drives; // 更新照片属性
    },


    // 编译照片
    onEditImage(type) {
      this.clickType = type;
      const url = type === 0 ? this.driveFront : this.driveAfter;
      this.editImageChange(url)
    },

    // 合成图片
    drawAndShareImage() {
      // 绘制背景海报到canvas
      // 长度85.6mm，宽度54mm // 身份证宽高 * 8 85.6mm * 54mm = 476mm * 476mm = 223.04mm * 223.04mm = 49802mm2
      const posterWidth = 684;      // 驾驶证宽度
      const posterHeight = 432;     // 驾驶证高度
      const a4Width = 1588;         // A4纸宽度
      const a4Height = 2246;        // A4纸高度

      const {driveFront, driveAfter} = this;

      // 检查是否已上传照片
      if (!driveFront && !driveAfter) {
        tips.toast('请先上传图片')
        return;
      }

      uni.showLoading({title: '加载中....', mask: true})
      // 微信小程序特有代码
      const context = uni.createCanvasContext('driveCanvas', this);

      context.fillStyle = "#FFFFFF";
      context.fillRect(0, 0, a4Width, a4Height);

      context.drawImage(driveFront, (a4Width - posterWidth) / 2, a4Height / 2 - 220 - posterHeight, posterWidth, posterHeight);
      context.drawImage(driveAfter, (a4Width - posterWidth) / 2, a4Height / 2, posterWidth, posterHeight);
      context.draw();

      setTimeout(() => {
        uni.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: a4Width,
          height: a4Height,
          destWidth: a4Width,
          destHeight: a4Height,
          canvasId: 'driveCanvas',
          success: (res) => {
            console.log("driveCanvas -=-=", res);
            // 上传图片到服务器
            uni.uploadFile({
              url: uploadImageServer,
              name: 'file',
              filePath: res.tempFilePath,
              success: (res) => {
                console.log("success: (res) => -=-=-", res)
                const {code, data: {url}} = JSON.parse(res.data);
                console.log("Upload success:", JSON.parse(res.data).data);
                if (code === 200) {
                  uni.navigateTo({url: `/pages/photo_pay/photo_pay?type=1&image=` + encodeURIComponent(JSON.stringify(url))})
                }
              },
              fail: (err) => {
                console.error('Upload failed:', err);
              }, complete: () => {
                uni.hideLoading()
              }
            });
          }
        });
      }, 2000)
    },
  }
}
</script>

<style>

</style>
